<?php

class CronJobsController extends CronAppController {

	var $name = 'CronJob';
	
	var $_log = null;
	
	function index() {
		$this->layout = 'basic';
		$this->set('jobs', $this->CronJob->findAll());
	}
	
	function runAll() {
		$this->layout = 'basic';
		$jobs = $this->CronJob->findAll();
		$log = array(array("Cron Session Started"));
		foreach ($jobs as $job) {
			if ($this->CronJob->shouldRun($job['CronJob']['frequency'])) {
				$log[] = array($job['CronJob']['controller'], '/', $job['CronJob']['action'], "runs");
				ob_start();
				$r = $this->requestAction('/' . $job['CronJob']['controller'] . '/' . $job['CronJob']['action']);
				$o = ob_get_contents();
				ob_end_clean();
				$log[] = array('Results:', $r);
				$log[] = array('Output:', $o);
			} else {
				$log[] = array($job['CronJob']['controller'], '/', $job['CronJob']['action'], "doesn't run");
			}
		}
		$log[] = array("Cron Session Complete");
		$this->set('log', $log);
		foreach($log as $logLine) {
			$this->log(join(' ', $logLine));
		}
	}
/**
 * API for logging events.
 *
 * @param string $msg Log message
 * @param int or string $type Error type.  Can use one of the constants defined in app/config/core.php.
 *    Otherwise, use 'cron' as the cron log.
 * @access
 */
	function log($msg, $type = 'cron') {
		if (!class_exists('CakeLog')) {
			uses('cake_log');
		}

		if (is_null($this->_log)) {
			$this->_log = new CakeLog();
		}

		if (!is_string($msg)) {
			ob_start();
			print_r ($msg);
			$msg=ob_get_contents();
			ob_end_clean();
		}

		switch($type) {
			case LOG_DEBUG:
				return $this->_log->write('debug', $msg);
			break;
			case LOG_ERROR:
				return $this->_log->write('error', $msg);
			break;
			default:
				return $this->_log->write($type, $msg);
			break;
		}
	}

}

?>